package com.sunseagear.wind.common.helper;

import com.sunseagear.common.oss.client.IOSSClient;
import com.sunseagear.common.oss.client.OSSClientFactory;
import com.sunseagear.common.oss.config.OssConfig;
import com.sunseagear.common.oss.exception.FileNameLengthLimitExceededException;
import com.sunseagear.common.oss.exception.InvalidExtensionException;
import com.sunseagear.common.utils.DateUtils;
import com.sunseagear.common.utils.PropertiesUtil;
import com.sunseagear.common.utils.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;

/**
 * 文件上传操作助手
 */
@Component
public class OSSUploadHelper {
    // 默认的文件名最大长度
    public static final int DEFAULT_FILE_NAME_LENGTH = 200;

    public static final int NO_LIMIT = -1;

    // 默认上传的地址
    private static final String DEFAULT_BASE_DIR = "upload";
    private String ossBaseDir = DEFAULT_BASE_DIR;


    private boolean needDatePath = false;
    private boolean originalName = false;

    //OSS上传客户端
    private String clientType = OSSClientFactory.CLIENT_LOCAL;
    private IOSSClient ossClient;

    public void init(OssConfig ossConfig) {
        ossBaseDir = ossConfig.getBaseDir();
        needDatePath = ossConfig.isNeedDatePath();
        originalName = ossConfig.isOriginalName();
        clientType = ossConfig.getClientType();
        this.ossClient = OSSClientFactory.build(clientType);
        Objects.requireNonNull(this.ossClient).init(ossConfig);
    }

    /**
     * 以默认配置进行文件上传
     *
     * @param request 当前请求
     * @param file    上传的文件
     *                添加出错信息
     */
    public String upload(HttpServletRequest request, MultipartFile file, String baseDir)
            throws FileSizeLimitExceededException, InvalidExtensionException, FileNameLengthLimitExceededException,
            IOException {
        String extension = SysConfigHelper.getInstance().getSysConfig("uploadFileType").getValue();
        String[] allowedExtension = extension.split(",");
        return upload(request, file, baseDir, allowedExtension);
    }

    /**
     * 以默认配置进行文件上传
     *
     * @param request          当前请求
     * @param file             上传的文件
     *                         添加出错信息
     * @param allowedExtension 允许上传的文件类型
     */
    public String upload(HttpServletRequest request, MultipartFile file, String baseDir, String[] allowedExtension)
            throws FileSizeLimitExceededException, InvalidExtensionException, FileNameLengthLimitExceededException,
            IOException {
        long maxSize = Long.parseLong(SysConfigHelper.getInstance().getSysConfig("uploadFileMaxSize").getValue());

        return upload(request, file, baseDir, allowedExtension, maxSize, needDatePath);
    }

    /**
     * 文件上传
     *
     * @param request          当前请求 从请求中提取 应用上下文根
     * @param baseDir          相对应用的基目录
     * @param file             上传的文件
     * @param allowedExtension 允许的文件类型 null 表示允许所有
     * @param maxSize          最大上传的大小 -1 表示不限制
     * @param needDatePath     是否需要日期目录和随机文件名前缀
     * @return 返回上传成功的文件名
     * @throws InvalidExtensionException            如果MIME类型不允许
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException                          比如读写文件出错时
     */
    public String upload(HttpServletRequest request, MultipartFile file, String baseDir,
                         String[] allowedExtension, long maxSize, boolean needDatePath)
            throws InvalidExtensionException, FileSizeLimitExceededException, IOException,
            FileNameLengthLimitExceededException {
        int fileNameLength = Objects.requireNonNull(file.getOriginalFilename()).length();
        if (fileNameLength > OSSUploadHelper.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(file.getOriginalFilename(), fileNameLength,
                    OSSUploadHelper.DEFAULT_FILE_NAME_LENGTH);
        }
        fileUploadValidate(file, allowedExtension, maxSize);
        String filename = extractFilename(file, baseDir, needDatePath);
        filename = StringUtils.trimDiagonal(filename);
        return ossClient.upload(file.getInputStream(), filename);
    }

    public String extractFilename(MultipartFile file, String baseDir, boolean needDatePath) {
        if (!StringUtils.isEmpty(this.ossBaseDir)) {
            if (!StringUtils.isEmpty(baseDir)) {
                baseDir = this.ossBaseDir + "/" + baseDir;
            } else {
                baseDir = this.ossBaseDir;
            }
        }
        String filename = file.getOriginalFilename();
        if (!originalName) {
            filename = DateUtils.long2DateTime(System.currentTimeMillis(), "yyyyMMddHHmmssSSS") + "."
                    + StringUtils.getExtensionName(filename);
        }
        if (needDatePath) {
            filename = datePath() + "/" + filename;
        }
        if (!StringUtils.isEmpty(baseDir)) {
            filename = baseDir + "/" + filename;
        }
        return filename;
    }

    /**
     * 日期路径 即年/月/日 如2013/01/03
     */
    private String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 是否允许文件上传
     *
     * @param file             上传的文件
     * @param allowedExtension 文件类型 null 表示允许所有
     * @param maxSize          最大大小 字节为单位 -1表示不限制
     * @throws InvalidExtensionException      如果MIME类型不允许
     * @throws FileSizeLimitExceededException 如果超出最大大小
     */
    public void fileUploadValidate(MultipartFile file, String[] allowedExtension, long maxSize)
            throws InvalidExtensionException, FileSizeLimitExceededException {

        String filename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());

        if (allowedExtension != null
                && !Arrays.stream(allowedExtension).toList().contains("*")
                && !isAllowedExtension(extension, allowedExtension)) {
            throw new InvalidExtensionException(allowedExtension, extension, filename);
        }

        long size = file.getSize();
        if (maxSize != NO_LIMIT && size > maxSize) {
            throw new FileSizeLimitExceededException("超出上传文件大小", size, maxSize);
        }
    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     */
    public boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.trim().equalsIgnoreCase(extension.trim())) {
                return true;
            }
        }
        return false;
    }


    public void delete(HttpServletRequest request, String filename) {
        if (StringUtils.isEmpty(filename)) {
            return;
        }
        ossClient.delete(filename);
    }
}
